var EventManager = function(world,networkManager){
    this.world = world;
    this.networkManager = networkManager;
    this.keys = {u:0,d:0,l:0,r:0};
    EventManager.Instance = this; // obligatoire pour le context 'this' de la mainLoop
    this.mainLoopTime = 40;
    this.actionMap;
}
EventManager.prototype = {

    initWorld : function(){
        var self = this;
        self.networkManager.putWorldInfo(function(){
            self.networkManager.getPersonages(function(){ // on recupère le personage
                    self.networkManager.refreshMap(function(){ // on rafraichit la map

                        self.world.init(function(){  // construction du monde

                        self.world.drawer.engine.scene.setCenter(self.world.worldCenter, null);
                        sheetengine.drawing.dimmedAlpha = 0.5;
                        Tile.prototype.__proto__ = Drawable.prototype; // only one instance of EventManager
                        Personage.prototype.__proto__ = Drawable.prototype; // only one instance of EventManager
                        UserPlantation.prototype.__proto__ = Drawable.prototype; // only one instance of EventManager
                        Planter.prototype.__proto__ = Action.prototype; // only one instance of EventManager
                        Attaquer.prototype.__proto__ = Action.prototype; // only one instance of EventManager
                        Arroser.prototype.__proto__ = Action.prototype; // only one instance of EventManager
                        Recolter.prototype.__proto__ = Action.prototype; // only one instance of EventManager
                        Fertiliser.prototype.__proto__ = Action.prototype; // only one instance of EventManager




                        self.actionMap = new Array();
                        var tileAction = new Array();
                        var plantAction = new Array();

                        tileAction.push(new Planter(this.world));
                        tileAction.push(new Attaquer());
                        tileAction.push(new Arroser());
                        tileAction.push(new Fertiliser());

                        self.actionMap["tile"] = tileAction;

                        plantAction.push(new Recolter());
                        plantAction.push(new Arroser("plant"));
                        plantAction.push(new Fertiliser("plant"));

                        self.actionMap["plant"] = plantAction;


                        self.initEvents(); // on initialise les évènements navigateur
                        self.mouseEvent();








                    });
                });
            });
        })
    },

    initEvents : function(){
        var self = this;
        window.onkeydown = function(event) { self.keysEvent(event, 1); }; // évènement clavier
        window.onkeyup = function(event) { self.keysEvent(event, 0); };
        setInterval(this.mainLoop, this.mainLoopTime); // boucle principale du jeu

    },

    mainLoop : function(){
        var self = EventManager.Instance; //
        var calAndDraw = self.movePersonage(self.world.getPersonage(),self.keys);
        self.world.drawer.engine.calc.calculateChangedSheets();
        self.world.drawer.engine.drawing.drawScene(calAndDraw.draw);
        if(this.world.worldInterface.hasSelected())
            self.world.worldInterface.displayDrawable(this.world.drawer);
    },


    movePersonage : function(personage,keys){
        personage.spriteSheetObject.sheets[0].canvasChanged();
        var targetp = personage.move(keys,this.world.drawer.engine,this.world.drawer.densityMap);
        if (targetp != null && personage.id == this.world.getPersonage().id){
            this.world.drawer.engine.scene.setCenter(targetp, null);
            this.networkManager.updatePersonage();
            this.world.moveWorldCenter();
            if (this.world.nearBoundary() && !this.networkManager.refreshing){
                this.networkManager.refreshMap();
                return { cal : false, draw: true };
            }
            return { cal : true, draw: true };
        }else{
            if (targetp != null ){
                return { cal : false, draw: true };
            }
        }
        return { cal : true, draw: false };
    },

    keysEvent : function(event, val) {
        var keyProcessed = 0;

        if (event.keyCode == '38' || event.keyCode == '87') {
            this.keys.u = val;
            keyProcessed = 1;
        }
        if (event.keyCode == '37' || event.keyCode == '65') {
            this.keys.l = val;
            keyProcessed = 1;
        }
        if (event.keyCode == '39' || event.keyCode == '68') {
            this.keys.r = val;
            keyProcessed = 1;
        }
        if (event.keyCode == '40' || event.keyCode == '83') {
            this.keys.d = val;
            keyProcessed = 1;
        }
        if (keyProcessed)
            event.preventDefault();

    },

    mouseEvent : function(){

        // mouse events

        var self = this;
        var canvas = this.world.drawer.engine.canvas;
        canvas.onclick = function(event) {
            // get the click coordinates
            console.log(self.actionMap);
            var puv = {
                u:event.clientX - sheetengine.canvas.offsetLeft + pageXOffset,
                v:event.clientY - sheetengine.canvas.offsetTop + pageYOffset
            };

            var pxy = sheetengine.transforms.inverseTransformPoint({
                u:puv.u + sheetengine.scene.center.u,
                v:puv.v + sheetengine.scene.center.v
            });
            self.getSelected(puv,pxy);

        };

    },

    getSelected : function(puv,pxy){

        //Boucle sur le tableau de personnages



        var self = this;
        for (var i = 0; i < this.world.personages.length; i++){
            if(this.world.personages[i].isSelected(this.world.drawer.engine,puv)){

                console.log("perso " + this.world.personages[i].name + " is selected");
                this.world.worldInterface.show(this.world.personages[i],[]);
                return;
            }
        }
        for (var i = 0; i < World.userPlants.length; i++){
            console.log(World.userPlants[i]);
            if(World.userPlants[i].isSelected(this.world.drawer.engine,puv)){
                var actions = new Array();

                for(var index in this.actionMap['plant']){
                    var action = this.actionMap['plant'][index];
                    console.log(this.actionMap['plant'][index]);
                    if(action.canDo(World.userPlants[i],this.world.getPersonage())){
                        actions.push(action);
                    }else{
                        console.log("can't do");
                    }
                }
                console.log(actions)
                this.world.worldInterface.show(World.userPlants[i],actions);
                return;

            }
        }

        for (var i = 0; i < this.world.map.length; i++){
            if(this.world.map[i].isSelected(this.world.drawer.engine,puv)){
                var actions = new Array();

                for(var index in this.actionMap['tile']){
                    var action = this.actionMap['tile'][index];
                    if(action.canDo(this.world.map[i],this.world.getPersonage())){
                        actions.push(action);
                    }
                }
                this.world.worldInterface.show(this.world.map[i],actions);
                return;

            }
        }

        this.world.worldInterface.handleClick(puv);


    }



}